package com.hu.controller;

import com.hu.mapper.UserMapping;
import com.hu.pojo.User;
import com.hu.utils.RestfulUtil;
import com.hu.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.hu.config.LoginHandlerInterceptor.useIdLocal;

@Controller
public class UserController {

    @Autowired
    UserMapping userMapping;

    @GetMapping("/user/getbyid/{userId}")
    @ResponseBody
    public String getOne(@PathVariable Integer userId){
        User user = userMapping.quaryById(userId);
        return RestfulUtil.toRestful(user);
    }

    @PostMapping("/user/getall")
    @ResponseBody
    public String getAll(){
        List<User> users = userMapping.quaryAll();
        return RestfulUtil.toRestful(users);
    }

    @PostMapping("/user/insert")
    @ResponseBody
    public String insert(User user){
        if (user.getUsername() == null || user.getPassword() == null){
            return RestfulUtil.toRestful(null,"用户名和密码不可为空",500);
        }
        User user1 = userMapping.quaryByUserName(user.getUsername());
        if (user1 != null){
            return RestfulUtil.toRestful(null,"当前用户名已被注册",501);
        }
        userMapping.addUser(user);
        return RestfulUtil.toRestful(null);
    }

    @GetMapping("/user/delete/{userId}")
    @ResponseBody
    public String insert(Integer userId){
        userMapping.deleteUser(userId);
        return RestfulUtil.toRestful(null);
    }

    @PostMapping("/user/login")
    @ResponseBody
    public String insert(String username,String password){
        User user = userMapping.quaryByUserName(username);
        if (user.getPassword().equals(password)){
            return RestfulUtil.toRestful(null, TokenUtil.createJWT(user),200);
        }else {
            return RestfulUtil.toRestful(null,"操作失败",401);
        }

    }

    @PostMapping("/user/getloginuser")
    @ResponseBody
    public String getLoginUser(){
        Integer userId = useIdLocal.get();
        if (userId == null){
            return RestfulUtil.toRestful(null,"用户id丢失",404);
        }
        return RestfulUtil.toRestful(userMapping.quaryById(userId));
    }






}
